﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using NGinnBPM.Lib.Interfaces;
using NGinnBPM.MessageBus.Impl.HttpService;
using NGinnBPM.MessageBus;
using System.IO;
using NGinnBPM.Lib.Schema;
using NGinnBPM.Lib.Data;

namespace NGinnBPM.Services.Website
{
    /// <summary>
    /// Task instance control servlet
    /// Handles task cancellation, completion, failing, update and state retrieval
    /// </summary>
    [UrlPattern("^/taskctrl/(?<command>cancel|complete|update|fail|getstate|getdata)/")]
    public class TaskControlServlet : ServletBase
    {
        public INGEnvironment Environment { get; set; }

        public  override void HandleRequest(IRequestContext ctx)
        {
            string inst = ctx.QueryString["instance"];
            if (inst == null || inst.Length == 0)
                throw new Exception("instance ID required (instance parameter)");

            string command = ctx.UrlVariables["command"];
            if (command == "cancel")
            {
                Environment.CancelTaskInstance(inst);
                ctx.Output.WriteLine("Success");
            }
            else if (command == "complete")
            {
            }
            else if (command == "update")
            {
                if (ctx.HttpMethod == "GET")
                {
                    Dictionary<string, object> d = new Dictionary<string, object>();
                    foreach (string k in ctx.QueryString.Keys) d[k] = ctx.QueryString[k];
                    Environment.UpdateTaskData(inst, d);
                    ctx.Output.WriteLine("Success");
                }
                else if (ctx.HttpMethod == "POST")
                {
                }
                else throw new Exception("Method unsupported");
                
            }
            else if (command == "fail")
            {
                Environment.ForceFailTask(inst, ctx.QueryString["error"]);
                ctx.Output.WriteLine("Success");
            }
            else if (command == "getstate")
            {
                string r = Environment.GetTaskState(inst);
                ctx.Output.Write(r);
            }
            else if (command == "getdata")
            {
                Dictionary<string, object> dob = Environment.GetTaskData(inst);
                ctx.Output.Write(DataUtil.ToJson(dob));
            }
        }
    }
}
